package com.qk.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.common.PageResult;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.enums.ParamEnum;
import com.qk.exception.CommonException;
import com.qk.mapper.RoleMapper;
import com.qk.service.DeptService;
import com.qk.service.UserService;
import com.qk.mapper.UserMapper;
import com.qk.util.JWTUtils;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author SweetHurt
 * @Date 2025-10-07 14:30:31
 * @Description 针对表【user(用户表)】的数据库操作Service实现
 */
@Service
@SuppressWarnings("all")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    private static final String DEFAULT_PASSWORD_SUFFIX = "123";
    private static final Integer USER_STATUS = 0;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        boolean b = BeanUtil.hasNullField(userLoginDTO);
        if (b) {
            CommonException.throwException(ParamEnum.PARAM_NOT_NULL_ERROR);
        }
        User dbUser = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (ObjectUtil.isNull(dbUser)) {
            CommonException.throwException(ParamEnum.LOGIN_USERNAME_OR_PASSWORD_ERROR);
        }
        if (ObjectUtil.equals(USER_STATUS, dbUser.getStatus())) {
            CommonException.throwException(ParamEnum.LOGIN_USER_STATUS_ERROR);
        }
        boolean isEqual = StrUtil.equals(dbUser.getPassword(),
                DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes()));
        if (!isEqual) {
            CommonException.throwException(ParamEnum.LOGIN_USERNAME_OR_PASSWORD_ERROR);
        }
        Role role = roleMapper.selectById(dbUser.getRoleId());
        return UserLoginVO.builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .roleLabel(ObjectUtil.isNull(role) ? null : role.getLabel())
                // TODO: 2025/10/10 获取token
                .token(JWTUtils.createToken(MapUtil.<String, Object>builder()
                        .put(JWTUtils.KEY_ID, dbUser.getId()).put(JWTUtils.KEY_USERNAME, dbUser.getUsername())
                        .build()))
                .build();
    }

    @Override
    public List<UserDO> getByDept(Integer deptId) {
        List<UserDO> users = userMapper.selectAllByDeptId(deptId);
        return users;
    }

    @Override
    public List<UserDO> getByRole(String label) {
        List<UserDO> users = userMapper.selectAllByRoleLabel(label);
        return users;
    }

    @Override
    public void updateById(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
    }

    @Override
    public UserDO getById(Integer id) {
        UserDO userDO = userMapper.selectById(id);
        return userDO;
    }

    @Override
    public void deleteUsers(String ids) {
        userMapper.deleteUsers(ids);
    }

    @Override
    public void addUser(User user) {
        boolean hasNull = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "createTime", "updateTime");
        if (hasNull) {
            CommonException.throwException(ParamEnum.PARAM_NOT_NULL_ERROR);
        }
        user.setPassword(DigestUtils.md5DigestAsHex(StrBuilder.create().append(user.getUsername()).append(DEFAULT_PASSWORD_SUFFIX).toString().getBytes()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insertUser(user);
    }

    @Override
    public PageResult<UserDO> listPage(UserDTO userDTO) {
        PageInfo<UserDO> pageInfo = PageHelper
                .startPage(userDTO.getPage(), userDTO.getPageSize())
                .doSelectPageInfo(() -> userMapper.selectAll(userDTO));
        return PageResult.<UserDO>builder()
                .total(Long.valueOf(pageInfo.getTotal()).intValue())
                .rows(pageInfo.getList())
                .build();
    }
}




